from flask import Blueprint, jsonify, request
from app.models.Skillc2 import Comment, News, User
from app import db
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

comment_bp = Blueprint('comment', __name__)

@comment_bp.route('/news/<int:news_id>/comments', methods=['GET'])
def get_comments(news_id):
    """获取新闻评论列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        
        # 只获取顶层评论（没有父评论的评论）
        comments = Comment.query.filter_by(
            NewsId=news_id,
            ParentId=None,
            IsDeleted=False
        ).order_by(Comment.CreateTime.desc()).paginate(page=page, per_page=per_page)
        
        return jsonify({
            'status': 'success',
            'data': {
                'items': [comment.to_dict() for comment in comments.items],
                'total': comments.total,
                'pages': comments.pages,
                'current_page': page,
                'has_next': comments.has_next,
                'has_prev': comments.has_prev
            }
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@comment_bp.route('/news/<int:news_id>/comments', methods=['POST'])
@jwt_required()
def create_comment(news_id):
    """创建评论"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
            
        news = News.query.get_or_404(news_id)
        data = request.get_json()
        
        if not data or not data.get('content'):
            return jsonify({
                'status': 'error',
                'message': '评论内容不能为空'
            }), 400
            
        comment = Comment(
            Content=data['content'],
            UserId=current_user_id,
            NewsId=news_id,
            ParentId=data.get('parent_id')
        )
        
        db.session.add(comment)
        
        # 更新新闻评论数
        news.CommentCount += 1
        
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '评论成功',
            'data': comment.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@comment_bp.route('/comments/<int:comment_id>', methods=['PUT'])
@jwt_required()
def update_comment(comment_id):
    """更新评论"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
            
        comment = Comment.query.get_or_404(comment_id)
        
        if comment.UserId != current_user_id:
            return jsonify({
                'status': 'error',
                'message': '只有评论作者可以修改评论'
            }), 403
            
        data = request.get_json()
        if not data or not data.get('content'):
            return jsonify({
                'status': 'error',
                'message': '评论内容不能为空'
            }), 400
            
        comment.Content = data['content']
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '评论更新成功',
            'data': comment.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@comment_bp.route('/comments/<int:comment_id>', methods=['DELETE'])
@jwt_required()
def delete_comment(comment_id):
    """删除评论（软删除）"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
            
        comment = Comment.query.get_or_404(comment_id)
        
        if comment.UserId != current_user_id:
            return jsonify({
                'status': 'error',
                'message': '只有评论作者可以删除评论'
            }), 403
            
        # 软删除评论
        comment.IsDeleted = True
        
        # 更新新闻评论数
        news = News.query.get(comment.NewsId)
        news.CommentCount -= 1
        
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '评论删除成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@comment_bp.route('/comments/<int:comment_id>/like', methods=['POST'])
@jwt_required()
def like_comment(comment_id):
    """点赞评论"""
    try:
        comment = Comment.query.get_or_404(comment_id)
        
        if comment.IsDeleted:
            return jsonify({
                'status': 'error',
                'message': '评论已删除'
            }), 404
            
        comment.LikeCount += 1
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '点赞成功',
            'data': {
                'like_count': comment.LikeCount
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 